package han.chensing.latos.maker.latos.config;

import han.chensing.latos.maker.latos.config.parameter.ConfigParameter;
import han.chensing.latos.maker.latos.config.parameter.ConfigValueParameter;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;

import java.lang.reflect.Constructor;
import java.util.HashMap;

public class ConfigFactory {
    private static ConfigFactory configFactory;

    public static ConfigFactory getInstance() {
        return configFactory ==null? configFactory =new ConfigFactory(): configFactory;
    }

    private static final HashMap<String,Class<? extends ConfigParameter>> classHashMap;
    static {
        classHashMap=new HashMap<>();
        classHashMap.put("value", ConfigValueParameter.class);
    }

    public ConfigParameter constructConfig(LuaTable luaTable){
        if (luaTable.keyCount()<=0) return null;
        String type = luaTable.get(1).tojstring();
        Class<? extends ConfigParameter> aClass = classHashMap.get(type);
        if (aClass==null)return null;
        try {
            Constructor<? extends ConfigParameter> constructor = aClass.getConstructor();
            ConfigParameter configParameter = constructor.newInstance();
            configParameter.loadConfigFromTable(constructTable(luaTable));
            return configParameter;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    private LuaValue[] constructTable(LuaTable luaTable){
        LuaValue[] out=new LuaValue[luaTable.keyCount()];
        LuaValue[] keys = luaTable.keys();
        int i=0;
        for (LuaValue key : keys) {
            LuaValue luaValue = luaTable.get(key);
            out[i++]=luaValue;
        }
        return out;
    }
}
